<?php

/**
 * ShopEx licence
 * wxpapi_ctl_goodsOrder
 *
 * @uses wxapi
 * @uses _frontpage
 * @package
 * @version $id$
 * @copyright  Copyright (c) 2005-2013 ShopEx Technologies Inc. (http://www.shopex.cn)
 * @author Tobias Schlitt <toby@php.net>
 * @license  http://ecos.shopex.cn/ ShopEx License
 */
class wxapi_ctl_goodsOrder extends wxapi_response
{

    /**
     * commitData
     *
     * @access public
     * @return void
     */
    public function commitData()
    {
        $product_id = floatval($_REQUEST['goodsId']);
        $num = intval($_REQUEST['num']);
        
        if(constant('TEST_MODE')){
            $apilogModel = app::get('apiactionlog')->model('apilog');
            $apilogData = array();
            $apilogData['apilog'] = time();
            $apilogData['original_bn'] = $product_id;
            $apilogData['task_name'] = '加购物车 Add Cart';
            $apilogData['log_type'] = 'other';
            $apilogData['api_type'] = 'response';
            $apilogData['calltime'] = time();
            $apilogData['createtime'] = time();
            $apilogData['last_modified'] = time();
            $apilogData['status'] = 'success';
            $apilogData['params'] = serialize($num);
            $apilogModel->insert($apilogData);
        }
        
        $is_fastbuy = false;
        if($product_id){          
            if( ! $num){
                self::api_error('购买数量错误');
            }
            
            $product = app::get('b2c')->model('products')->getRow('goods_id,product_id,store', ['product_id'=>$product_id]);            
            $is_fastbuy = true;//快速购买
            $_POST = [
                'btype' => 'is_fastbuy',
                'mini_cart' => 'true',
                'min'=>1,
                'max' => $product['store'],
                'goods' => [
                    'goods_id' => $product['goods_id'],
                    'product_id' => $product['product_id'],
                    'num' => $num,
                ],
                0 => 'goods',
            ];
            $ret = kernel::single('wxapi_respositories_cart_cart')->add('goods');
        }
        
        $pagedata = kernel::single('wxapi_respositories_cart_cart')->checkout($is_fastbuy);        
        //self::return_json($pagedata);
        
        $used_coupon = '';
        $used_coupon_name = '';
        if($pagedata['aCart']['object']['coupon']){
            $used_coupon = $pagedata['aCart']['object']['coupon'][0]['obj_ident'];
            $used_coupon_name = $pagedata['aCart']['object']['coupon'][0]['name'];
            $used_coupon = str_replace('coupon_', '', $used_coupon);
        }
        
        $point_data = array(
            'max_discount_value_money' => 0,
            'max_discount_value_point' => 0,
            'discount_rate' => 0,
        );
        if($pagedata['order_detail']['point_data']){
            $point_data = $pagedata['order_detail']['point_data'];
        }

        //$coupon_lists = $this->get_coupon_list($pagedata['coupon_lists']);
        $coupon_lists = array();//todo 暂时没有优惠券
        
        $return = [
            'reason' => '',
            'code' => 0,
            'coupon_lists' => $coupon_lists,
            'point_data' => $point_data,
            'totalPrice' => $pagedata['order_detail']['cost_item'],
            'actualPrice' => $pagedata['order_detail']['final_amount'],
            'hasDefaultAddress' => count($pagedata['def_addr']) ? true : false,
            'deduScore' => 1220, //$pagedata['order_detail']['final_amount']['totalConsumeScore'],
            'reduceFee' => 0, //$pagedata['order_detail']['final_amount']['discount_amount'],
            'goodsList' => $this->get_goodsListByCart($pagedata['aCart']['object']['goods']),
            'userScore' => 0,
            'canUseScore' => 0,
            "giftsList"=> $this->get_gifts($pagedata['aCart']),
            "promoFee"=> $pagedata['aCart']['subtotal_discount'],
            "totalgoodsPrice"=> $pagedata['order_detail']['final_amount'],
            "deduFee"=>0,
            "promoId"=> "",
            "totalfreight"=> 0,
            //'def_addr' => $this->get_defaultAddressBydefAddr($pagedata['def_addr']),
            'def_addr' => '',
            'used_coupon' => $used_coupon,
            'used_coupon_name' => $used_coupon_name,
            'promotions' => $this->get_order_promotions($pagedata['aCart']),
        ];
        self::return_json($return);       
    }
    
    public function get_order_promotions($aCart)
    {
        $promotions = array();  
        if($aCart['promotion']['order']){
            foreach($aCart['promotion']['order'] as $v){
                $promotions[] = array(
                    'name' => $v['name'],
                    'desc_tag' => $v['desc_tag'],
                );
            }
        }
        
        //todo $aCart['promotion']['goods'] 没有处理，暂时没用到商品促销
        return $promotions;
    }
    
    public function get_coupon_list($coupon_lists)
    {
        $data = array();
        foreach($coupon_lists as $v){
            $data[] = array(
                'memc_code' => $v['memc_code'],
                'cpns_name' => $v['coupons_info']['cpns_name'],
                'cpns_id' => $v['cpns_id'],
            );
        }   
        return $data;
    }
    
    public function get_gifts($aCart)
    {
        $gifts = array();
        //处理订单的赠品
        if($aCart['object']['gift']['order']){
            foreach($aCart['object']['gift']['order'] as $v){
                $gifts[] = array(
                    'goodsSkuValName' => $v['spec_info'],
                    'goodsName' => $v['name'],
                    'thumLogo' => $v['thumbnail'],
                    'num' => $v['quantity'],
                    'price' => round($v['price']['price'], 2),
                );
            }            
        }
        
        //处理商品的赠品
        if($aCart['object']['goods']){
            foreach($aCart['object']['goods'] as $v){
                if($v['gift']){
                    foreach($v['gift'] as $v){
                        $gifts[] = array(
                            'goodsSkuValName' => $v['spec_info'],
                            'goodsName' => $v['name'],
                            'thumLogo' => $v['thumbnail'],
                            'num' => $v['quantity'],
                            'price' => round($v['price']['price'], 2),
                        );
                    }                    
                }                
            }            
        }
        
        return $gifts;
    }

    /**
     * 下单结算
     *
     * @access public
     * @return void
     */
    //   openId=oADLw0EvIHC5mcROtQglRAzJilQI&
    //   goodsId=&
    //   receiverInfoId=2c9257a16136c3d60162e6fa8c934d82&
    //   businessMessage=&
    //   formId=a16c4de3cd31b665b4c319891aac3b4b&
    //   reduceScore=0&
    //   promoId=&
    //   promoFee=0&
    //   couponsId=&
    //   sign=389f8b63e2384a4d89067c13d2e3de6c&
    //   time=20180507141143'
    public function saveBycart()
    {
        //省市区，地址，电话，收货人，fastbuy，留言，发票，优惠券code，是否使用积分
        //province,,,,,,,,,,
        
        
        $data = $this->_request->get_params(true);
        //self::return_json($params);
        $params = array(
            //'province' => $params['province'],
            //'city' => $params['city'],
            //'district' => $params['district'],
            //'address' => $params['address'],
            //'mobile' => $params['mobile'],
            //'receiver_name' => $params['receiver_name'],
            'addr_id' => intval($data['addr_id']),
            'is_fastbuy' => intval($data['is_fastbuy']),// 0 1 表示是否快速购买
            'buyer_message' => $data['buyer_message'],
            'invoice_title' => $data['invoice_title'],
            'coupon_code' => $data['coupon_code'],
            'use_points' => intval($data['use_points']),//0 1 表示是否使用积分
        );
        
        if(constant('TEST_MODE')){
            $apilogModel = app::get('apiactionlog')->model('apilog');
            $apilogData = array();
            $apilogData['apilog'] = time();
            $apilogData['original_bn'] = '';
            $apilogData['task_name'] = '下单结算 saveBycart';
            $apilogData['log_type'] = 'other';
            $apilogData['api_type'] = 'response';
            $apilogData['calltime'] = time();
            $apilogData['createtime'] = time();
            $apilogData['last_modified'] = time();
            $apilogData['status'] = 'success';
            $apilogData['params'] = serialize($data);
            $apilogModel->insert($apilogData);
        }
        
        if($params['use_points'] == 1){
            $params['point'] = array(
                'rate' => $data['point_rate'],
                'score' => $data['point_score'],
            );
        }
        
        $params['purchase']['addr_id'] = $params['addr_id'];
        $params['address'] = $this->getAddressByreceiverInfoId($params['addr_id']);
        $params['md5_cart_info'] = md5(time());
        $params['extends_args'] = '{';
        $params['shipping'] = $this->getWepyShipping();
        
        //支付方式
        $params['payment']['currency'] = 'CNY';
        $params['payment']['pay_app_id'] = '{"pay_app_id":"wxpaywxapp","payment_name":"微信支付"}';
        $params['coupon'] = $params['coupon'];
        $params['memo'] = $params['buyer_message'];
        
        //self::return_json($params);

        $pagedata = kernel::single('wxapi_respositories_orders_create')->create($params);
        $return = [
            "result"=> "0",
            "msg"=> "",
            "code"=> "0",
            "tradeNo"=> $pagedata['order_id'],
            "outOfStockGoodsList"=> [],
            "offLineGoodsList"=> []
        ];
        echo json_encode($return);
        exit;
    }

    /**
     * toPay
     *
     * @access public
     * @return void
     */
    public function toPay()
    {
        $order_id = $_REQUEST['orderNo'];
        $orderInfo = app::get('b2c')->model('orders')->getRow('order_id,final_amount,pay_status', ['order_id'=>$order_id]);
        if($orderInfo['pay_status'] != 0)
            return $this->splash('error',$url,'订单已支付，请勿重复支付!');
        
        $_POST = [
            'payment' => [
                'order_id' => $order_id,
                'def_pay' => [
                    'cur_money' => $orderInfo['final_amount'],
                    'pay_app_id' => 'wxpaywxapp',
                ],
                'memo'=>'',
            ],
        ];

        $pagedata = kernel::single('wxapi_respositories_orders_paycenter')->dopayment('order', false);
        echo $pagedata;
        exit;
    }

    public function get_goodsListByCart($cart)
    {
        $goodsList = [];
        //return $cart;
        foreach($cart as $item)
        {
            if($item['is_check'] == 0) continue;
            
            $goods = [];
            $goods["brandName"] = '';
            $goods["canWhole"] = false;
            $goods["goodsId"] = $item['obj_items']['products'][0]['goods_id'];
            $goods["goodsName"] = $item['obj_items']['products'][0]['name'];// "印花圆领短袖纯棉T恤  T18C073",
            $goods["goodsSkuId"] = $item['obj_items']['products'][0]['product_id'];//: "2c9257a16136c3d60162e1ad438b4bd0",
            $goods["goodsSkuValName"] = (string)$item['obj_items']['products'][0]['spec_info'];//: "[\"S\",\"白色\"]",
            //$goods["goodsSkuValName"] = json_encode(explode('、', $item['obj_items']['products'][0]['spec_desc']));//: "[\"S\",\"白色\"]",
            $goods["goodsSkuVals"] = '';//explode('、', $item['obj_items']['products'][0]['spec_desc']); //: ["S", "白色"],
            $goods["id"] = $item['obj_items']['products'][0]['product_id'];//: "2c9257a16136c3d60162e76c7fff4da7",
            $goods['logo'] = base_storager::image_path($item['obj_items']['products'][0]['thumbnail']); //"logo": "http://sujiefs.com/upload/images/20180420/201804201408181830759.jpg",
            $goods["minBuyNum"]= 1;
            $goods["num"] = $item['quantity'];
            $goods["orgPrice"] = $item['obj_items']['products'][0]['price']['price'];//: "79",
            $goods["price"]= sprintf('%.2f',$item['obj_items']['products'][0]['price']['price']);//: "79",
            $goods["priceSubtotal"] = $item['obj_items']['products'][0]['price']['buy_price'];//: "79",
            $goods["status"] = 1;//: 1,
            $goods["stockNum"] = 10;//: 10,
            $goods["thumLogo"] = base_storager::image_path($item['obj_items']['products'][0]['thumbnail']);//: "http://sujiefs.com/upload/images/20180420/201804201408181830759_thumbnail.jpg",
            $goods["wholeNum"] = 3;//: 3,
            $goods["wholePrice"] = $item['obj_items']['products'][0]['price']['buy_price'];//: 75

            $goodsList[] = $goods;

        }
        return $goodsList;

    }

   
    public function get_defaultAddressBydefAddr($addr)
    {
        $areaArr = explode(':', $addr['area']);
        $areaArr2 = explode('/', $areaArr[1]);

        $ret_addr = [];
        $ret_addr["addressDetail"] = $addr['addr'];//"赛季茶几黎明自知之明吗",
        $ret_addr["alias"] =  "";
        $ret_addr["areaCode"] = $addr['zip'];//"110101",
        $ret_addr["areaName"] =  $areaArr2[1];
        $ret_addr["cityCode"] = $areaArr[2];//: "110100",
        $ret_addr["cityName"] = $areaArr2[2];//: "市辖区",
        $ret_addr["createTime"] = [
            "date"=> 21,
            "day"=> 6,
            "hours"=> 14,
            "minutes"=> 53,
            "month"=> 3,
            "nanos"=> 0,
            "seconds"=> 22,
            "time"=> 1524293602000,
            "timezoneOffset"=> -480,
            "year"=> 118

        ];
        $ret_addr["email"]= "";
        $ret_addr["id"] = $addr['addr_id'];// "2c9257a16136c3d60162e6fa8c934d82",
        $ret_addr["isDef"]= 1;
        $ret_addr["mobile"] = $addr['moblie'];//: "13122223333",
        $ret_addr["phone"] = $addr['tel'];//: "",
        $ret_addr["postalCode"] = '';//: "",
        $ret_addr["provinceCode"] = $addr['zip'];//: "110000",
        $ret_addr["provinceName"] = $areaArr2[0];//: "北京市",
        $ret_addr["receiverName"] = '';//: "银行",
        $ret_addr["updateTime"] = $ret_addr['createTime']; //: 
        $ret_addr["userAccount"] = $addr['member_id'];//: "93697408",
        $ret_addr['userId'] = $addr['member_id'];
        return $ret_addr;
    }

    public function getAddressByreceiverInfoId($addr_id)
    {
        $addr = app::get('b2c')->model('member_addrs')->getRow('addr_id,area');
        $areaArr = explode(':', $addr['area']);

        return json_encode(
            [
                'addr_id'=>$addr_id,
                'area'=> $areaArr[2]
            ]
        );
    }
    
    //将微信地址保存到本地数据库
    public function saveWxAddress($data = array())
    {
        if( ! $data) {
            $data = $this->_request->get_params(true);
        }
        
        $member_id  = $this->member_info['member_id'];
        if( ! $member_id){
            self::api_error('用户未登录');
        }
        $addr_data = array(
            'area' => (string)$data['area'],//'mainland:上海/上海市/卢湾区:24',
            'addr' => (string)$data['address'],
            'name' => (string)$data['receiver_name'],
            'mobile' => (string)$data['mobile'],
            'tel' => (string)$data['tel'],
            'member_id' => $this->member_info['member_id'],
        );        
        
        $err_msg = '';
        $rs = kernel::single('b2c_member_addrs')->get_addr_id($addr_data);
        if($rs){
            return $rs;
        } else {
            $save_data = kernel::single('b2c_member_addrs')->purchase_save_addr($addr_data,$member_id,$err_msg);
        }
        
        if($save_data){
            return $save_data;
        } else {
            self::api_error($err_msg);
        }
    }
    
    /**
     * 获取运费
     * 1.传入微信地址
     * 2.获取购物车数据
     * 3.获取默认配送
     * 4.计算运费
     **/
    public function getPostFee($data = array())
    {
        if( ! $data) {
            $data = $this->_request->get_params(true);
        }

        //获取购物车数据
        $is_fastbuy = $data['is_fastbuy'] ? true : false;
        $mCart = app::get('b2c')->model('cart');
        $aData['is_fastbuy'] = $is_fastbuy;
        $aData['apply_platform'] = '2';
        $aCart = $mCart->get_objects($aData);

        //转换微信地址
        if( $data['province'] && $data['city'] && $data['district'] ){
            //微信地址
            $addrData = array(
                'province' => urldecode($data['province']),
                'city' => urldecode($data['city']),
                'district' => urldecode($data['district']),
            );
            
            //将微信地址转换成本地地址
            $def_addr = $this->wxToLocalRegion($addrData, $msg);
            
            $addrData['area'] = "mainland:".$def_addr['province']."/".$def_addr['city']."/".$def_addr['county'].":".$def_addr['region_id']."";
            $addrData['address'] = $data['address'] ? $data['address'] : '空测试数据';
            $addrData['receiver_name'] = $data['receiver_name'] ? $data['receiver_name'] : '空数据';
            if($data['mobile'] && preg_match("/1[\d]{10}/", $data['mobile'])){
                $addrData['mobile'] = $data['mobile'];
            } else {
                $addrData['tel'] = $data['mobile'] ? $data['mobile'] : '021-33251818';
            }
            
            //转换成addr_id
            $local_addr = $this->saveWxAddress($addrData);
            $addr_id = $local_addr['addr_id'];
            //self::return_json($local_addr);             
        }else{
            self::api_error('收货地址不能为空');
        }
        if( !$def_addr ){
            return self::api_error('收货地址获取失败');
        }
        $aCart['def_addr'] = $def_addr;

        //获取商品总重量
        $weight = $aCart['subtotal_weight'];

        //获取默认配送方式  @todo 暂时取第一个 此处应该有默认选取规则
        $dlytypeMdl = app::get('b2c')->model('dlytype');
        $shippings = $dlytypeMdl->getList('*',array('has_code'=>'false','dt_status'=>'1'));

        //检测是否包邮
        //self::return_json($aCart);
        if (!isset($aCart['is_free_shipping']) or !$aCart['is_free_shipping']){
            if ($aCart['object']['goods']){
                foreach ($aCart['object']['goods'] as $item_obj){
                    if (isset($item_obj['is_free_shipping']) && $item_obj['is_free_shipping']){
                        $aCart['is_free_shipping'] = true;
                    }
                }
            }
        }

        //计算运费总额        
        if( $aCart['is_free_shipping'] ){
            $cost_freight = 0;
        } else {
            $cost_freight = $this->freight($aCart, $shippings[0]);
        }

        $api_data = array(
            'postFee' => sprintf("%.2f",$cost_freight),
            'addr_id' => $addr_id,
        );
        return self::return_json($api_data);
    }

    public function getWepyShipping()
    {
        return '{"id":1,"has_cod":"false","dt_name":"快递","money":"10"}';
    }

    //对比并转换成本地地区 微信地址转换为本地地址
    function wxToLocalRegion($addrData, &$msg='')
    {       
        $deliveryarea = app::get('ectools')->model('regions');

        $grade_name = array();
        $region_data = array();
        $region_path = ',';//地区路径

        $first = $this->area_format($addrData['province']);

        //获取一级地区
        $rs = $deliveryarea->dump(array('local_name|head'=>$first,'region_grade'=>'1'), 'package,region_id,local_name');
        if( ! $rs ){
            $rs = array(
                'local_name' =>$first,
                'package' =>'mainland',
                'region_grade' =>'1',
            );
            $deliveryarea->save($rs);
            
            //更新region_path字段
            if($rs['region_id']){
                $region_path .= $rs['region_id'].",";
                $deliveryarea->update(array('region_path'=>$region_path), array('region_id'=>$rs['region_id']));
            }            
        } else {
            $region_path .= $rs['region_id'].",";
        }
        $first_id = $rs['region_id'];
        $grade_name[$first_id] = $rs['local_name'];
        $region_data['province'] = $rs['local_name'];        

        //二级地区
        $city = $addrData['city'];
        $rs = $deliveryarea->dump(array('local_name|head'=>$city,'region_grade'=>'2','p_region_id'=>$first_id), 'package,region_id,local_name');
        if( ! $rs){
            $rs = array(
                'local_name' =>$city,
                'p_region_id' =>$first_id,
                'package' =>'mainland',
                'region_grade' =>'2',
            );
            $deliveryarea->save($rs);
            
            //更新region_path字段
            if($rs['region_id']){
                $region_path .= $rs['region_id'].",";
                $deliveryarea->update(array('region_path'=>$region_path), array('region_id'=>$rs['region_id']));
            }
        } else {
            $region_path .= $rs['region_id'].",";
        }
        $city_id = $rs['region_id'];
        $grade_name[$city_id] = $rs['local_name'];
        $region_data['city'] = $rs['local_name'];
        
        //三级地区
        $counties = $addrData['district'];
        $rs = $deliveryarea->dump(array('local_name|head'=>$counties,'region_grade'=>'3','p_region_id'=>$city_id), 'package,region_id,p_region_id,local_name');
        if( ! $rs){
            $rs = array(
                'local_name' =>$counties,
                'p_region_id' =>$city_id,
                'package' =>'mainland',
                'region_grade' =>'3',
            );
            $deliveryarea->save($rs);
            
            //更新region_path字段
            if($rs['region_id']){
                $region_path .= $rs['region_id'].",";
                $deliveryarea->update(array('region_path'=>$region_path), array('region_id'=>$rs['region_id']));
            }
        } else {
            $region_path .= $rs['region_id'].",";
        }
        $counties_id = $rs['region_id'];
        $grade_name[$counties_id] = $rs['local_name'];
        $region_data['county'] = $rs['local_name'];

        $country = $deliveryarea->getByRegstrName($region_data);
        if( !$country ){
            $msg = "地区验证失败";
            return false;
        }
        $country = array_merge($country,$region_data);
        return $country;
    }
    
    /**
     * 前端店铺三级地区本地临时转换
     * @param $area
     */
    public function area_format($area)
    {
        $all_province = array(
            '内蒙古自治区' => '内蒙古',
            '广西壮族自治区' => '广西',
            '西藏自治区' => '西藏',
            '宁夏回族自治区' => '宁夏',
            '新疆维吾尔自治区' => '新疆',
            '香港特别行政区' => '香港',
            '澳门特别行政区' => '澳门',
            '江苏省' => '江苏',
            '山东省'=>'山东',
            '广东省'=>'广东',
            '吉林省'=>'吉林',
            '湖南省'=>'湖南',
            '河北省'=>'河北',
            '浙江省'=>'浙江',
            '四川省'=>'四川',
            '山西省'=>'山西',
            '福建省'=>'福建',
            '黑龙江省'=>'黑龙江',
            '甘肃省'=>'甘肃',
            '陕西省'=>'陕西',
            '安徽省'=>'安徽',
            '海南省'=>'海南',
            '云南省'=>'云南',
            '河南省'=>'河南',
            '辽宁省'=>'辽宁',
            '湖北省'=>'湖北',
            '江西省'=>'江西',    
            '贵州省'=>'贵州',   
            '青海省'=>'青海', 
            '台湾省'=>'台湾',
            '上海市'=>'上海',
            '北京市'=>'北京',
            '天津市'=>'天津',
            '重庆市'=>'重庆',
        );
        if (isset($all_province[$area])){
            return $all_province[$area];
        }else{
            return $area;
        }
    }

    //运费计算
    public function freight($cart, $shipping){
        $objMath = kernel::single('ectools_math');
        $cart_info = $cart;
        $cost_item = $cart_info['subtotal'];//购物车里商品总费用
        $items_weight = $cart_info['subtotal_weight'];//购物车里商品总重量
        
        $objCurrency = app::get('ectools')->model('currency');;
        $arrDefCurrency = $objCurrency->getDefault();
        $strDefCurrency = $arrDefCurrency['cur_code'];
        $aCur = $objCurrency->getcur($sdf_order['cur']);

        if($shipping['dt_id'])
        {
            $dlytype = app::get('b2c')->model('dlytype');//配送方式
            $dlytype_info = $dlytype->dump($shipping['dt_id'],'*');
            /** 阶梯费用只能根据优惠后的金额来处理 - 除去商品优惠和订单优惠后的最终价格 **/
            $subtotal_order_after = $objMath->number_minus(array($cost_item, $cart_info['discount_amount_prefilter'], $cart_info['discount_amount_order']));
            if ($dlytype_info['is_threshold'])
            {
                if ($dlytype_info['threshold'])
                {
                    $dlytype_info['threshold'] = unserialize(stripslashes($dlytype_info['threshold']));
                    if (isset($dlytype_info['threshold']) && $dlytype_info['threshold'])
                    {
                        foreach ($dlytype_info['threshold'] as $res)
                        {
                            if ($res['area'][1] > 0)
                            {
                                if ($subtotal_order_after >= $res['area'][0] && $subtotal_order_after < $res['area'][1])
                                {
                                    $dlytype_info['firstprice'] = $res['first_price'];
                                    $dlytype_info['continueprice'] = $res['continue_price'];
                                }
                            }
                            else
                            {
                                if ($subtotal_order_after >= $res['area'][0])
                                {
                                    $dlytype_info['firstprice'] = $res['first_price'];
                                    $dlytype_info['continueprice'] = $res['continue_price'];
                                }
                            }
                        }
                    }
                }
            }

            if (!$dlytype_info['setting'])
            {
                if($cart_info['def_addr']['region_id']){
                    $area_id = $cart_info['def_addr']['region_id'];
                }
                // else{
                //     $arrArea = explode(':', $sdf_order['area']);
                //     $area_id = $arrArea[2];
                // }
                if (isset($dlytype_info['area_fee_conf']) && $dlytype_info['area_fee_conf'])
                {
                    $area_fee_conf = unserialize($dlytype_info['area_fee_conf']);

                    foreach($area_fee_conf as $k=>$v)
                    {
                        $areas = explode(',',$v['areaGroupId']);

                        // 再次解析字符
                        foreach ($areas as &$strArea)
                        {
                            if (strpos($strArea, '|') !== false)
                            {
                                $strArea = substr($strArea, 0, strpos($strArea, '|'));
                                // 取当前area id对应的最上级的区域id
                                $objRegions = app::get('ectools')->model('regions');
                                $arrRegion = $objRegions->dump($area_id);
                                while ($row = $objRegions->getRegionByParentId($arrRegion['p_region_id']))
                                {
                                    $arrRegion = $row;
                                    $tmp_area_id = $row['region_id'];
                                    if ($tmp_area_id == $strArea)
                                    {
                                        $area_id = $tmp_area_id;
                                        break;
                                    }
                                }
                            }
                        }
                        if(in_array($area_id,$areas)) {
                            //如果地区在其中，优先使用地区设置的配送费用，及公式
                            if ($dlytype_info['firstprice'])
                            $dlytype_info['firstprice'] = $v['firstprice'];
                            $dlytype_info['continueprice'] = $v['continueprice'];
                            $dlytype_info['dt_expressions'] = $v['dt_expressions'];
                            break;
                        }
                    }

                    //验证地区是否在配送范围 @todo
                    
                }
            }
            $cost_freight = @utils::cal_fee($dlytype_info['dt_expressions'],$items_weight,$cost_item,$dlytype_info['firstprice'],$dlytype_info['continueprice']);//配送费
        }
       
        return $cost_freight;
    }

    //积分兑现
    public function getPointsDiscount()
    {
        $total_amount = floatval($_REQUEST['total_amount']);

        // $total_amount = 30.50; //测试
        
        $return = array(
            'score_total'=>0,
            'score_dedu_num'=>0,
            'score_dedu_total'=>0,
        );
        
        //获取用户可用积分
        // $mem_point = app::get('b2c')->model('member_point');
        // $total_point = $mem_point->get_total_count($this->member_info['member_id']);
        // $return['score_total'] = intval($total_point);

        $obj_member = app::get('pointprofessional')->model('members');
        $real_total_point = $obj_member->get_real_point($this->member_info['member_id']);
        $real_total_point = $real_total_point - $obj_member->get_freez_point($sdf_order['member_id']);
        $return['score_total'] = intval($real_total_point);

        //订单金额为0 或者积分为0  无需抵扣
        if( ((float)$total_amount <= 0) || ($return['score_total']<=0) ){
            // return self::api_error('订单金额或积分为0无需抵扣');
            return self::return_json($return);
        }

        //禁用积分抵扣
        $site_point_usage = app::get('b2c')->getConf('site.point_usage');
        if( $site_point_usage != '2' ){
            // return self::api_error('当前积分只用于兑换');
            return self::return_json($return);
        }

        $site_point_deductible_value = app::get('b2c')->getConf('site.point_deductible_value');
        $site_point_max_deductible_value = app::get('b2c')->getConf('site.point_max_deductible_value');
        $site_point_max_deductible_method = app::get('b2c')->getConf('site.point_max_deductible_method');

        $objMath = kernel::single('ectools_math');
        $point_dis_value = $objMath->number_multiple(array($site_point_deductible_value, $return['score_total']));
        
        $real_total_money = $objMath->number_multiple(array($real_total_point, $site_point_deductible_value));

        //计算可用于抵扣的积分
        switch($site_point_max_deductible_method){
            case '1': // 每一笔订单最大的抵扣金额。
                if ($point_dis_value > $site_point_max_deductible_value)
                {
                    $point_dis_value = $site_point_max_deductible_value;
                }
                if ($site_point_max_deductible_value > $total_amount){
                    $max_point_amount = $total_amount;
                }else{
                    $max_point_amount = $site_point_max_deductible_value;
                }
                if ($max_point_amount > $real_total_money){
                    $max_point_amount = $real_total_money;
                }
                
                if ($point_dis_value > $max_point_amount){
                    $point_dis_value = $max_point_amount;
                }

                $total_point = floor($objMath->number_div(array($site_point_max_deductible_value, $site_point_deductible_value)));
                $subtotal_consume_score = floor($objMath->number_div(array($point_dis_value, $site_point_deductible_value)));
                $point_dis_value = $objMath->number_multiple(array($site_point_deductible_value, $subtotal_consume_score));
                if ($point_dis_value > $real_total_money){
                    $point_dis_value = $real_total_money;
                }
                break;

            case '2': // 每一笔订单最大的抵扣比例。
                if ($site_point_max_deductible_value > 1)
                {
                    $site_point_max_deductible_value = 1;
                }
                $max_point_amount = $objMath->number_multiple(array($total_amount, $site_point_max_deductible_value));
                if ($point_dis_value > $max_point_amount)
                {
                    $point_dis_value = $max_point_amount;
                }
                if ($max_point_amount > $real_total_money)
                    $max_point_amount = $real_total_money;
                $total_point = floor($objMath->number_div(array($max_point_amount, $site_point_deductible_value)));
                $subtotal_consume_score = floor($objMath->number_div(array($point_dis_value, $site_point_deductible_value)));
                $point_dis_value = $objMath->number_multiple(array($site_point_deductible_value, $subtotal_consume_score));
                if ($point_dis_value > $real_total_money){
                    $point_dis_value = $real_total_money;
                }
                break;
        }
        if( isset($subtotal_consume_score) ){
            $return['score_dedu_num'] = (int)$subtotal_consume_score;
        }
        if( isset($point_dis_value) ){
            $return['score_dedu_total'] = round($point_dis_value, 2);
        }
        // echo "<pre>";var_dump($return);exit;
        return self::return_json($return);
    }

    //获取订单总金额
    public function getTotal(){
        $_POST['is_fastbuy'] = 'true';

        $member = self::user_auth();
        if(empty($member['member_id'])){
            return self::api_error('请先登录');
        }

        if( isset($_POST['is_fastbuy']) ){
            $aData['is_fastbuy'] = $_POST['is_fastbuy'];
        }
        $aData['apply_platform'] = '1';
        $aCart = app::get('b2c')->model("cart")->get_objects($aData);  //获取购物车数据

        $return_data = [
            'subtotal' => (float)$aCart['subtotal'],//商品总金额
            'subtotal_discount' => (float)$aCart['subtotal_discount'], //优惠总金额
            'subtotal_price' => (float)$aCart['subtotal_price'], //商品原始金额
        ];
        // echo "<pre>";var_dump($aCart,$aCart['subtotal'],$aCart['subtotal_discount']);exit;

        return self::return_json($return_data);
    }


}


